package cn.outsourcing.supermarket.vo;

import cn.outsourcing.supermarket.common.constants.WechatConstants;
import cn.outsourcing.supermarket.dto.WxUserInfoDTO;
import cn.outsourcing.supermarket.common.utils.JwtUtils;
import cn.outsourcing.supermarket.common.utils.StrUtils;
import cn.outsourcing.supermarket.po.HiolabsUser;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.util.HashMap;

/**
 * 微信用户值对象
 *
 * @author gzkemays
 * @since 2021/10/21 15:30
 */
@Data
@Builder
@AllArgsConstructor
public class WxUserVO {
  String token;
  WxUserInfoDTO userInfo;
  Boolean is_new;

  /**
   * 进行对象复制
   *
   * @param user {@link HiolabsUser} 用户PO表对象
   * @param sessionKey J2S 校验返回的 sessionKey
   */
  public WxUserVO(HiolabsUser user, String sessionKey) {
    WxUserInfoDTO wxUserInfoEntity = new WxUserInfoDTO();
    BeanUtils.copyProperties(user, wxUserInfoEntity);
    wxUserInfoEntity.setId(user.getId());
    wxUserInfoEntity.setNickname(StrUtils.getStrByBase64(user.getNickname()));
    this.token =
        JwtUtils.settings()
            .build()
            .createTokenByMapNotExp(
                new HashMap<String, Object>(3) {
                  {
                    put(WechatConstants.SESSION_KEY, sessionKey);
                    put(WechatConstants.OPEN_ID, user.getWeixinOpenid());
                    put("user_id", user.getId());
                  }
                });
    this.is_new = false;
    this.userInfo = wxUserInfoEntity;
  }
}
